import React, { useRef, useEffect, useState } from 'react';
import {
  Box,
  Paper,
  Typography,
  Avatar,
  IconButton,
  Tooltip,
  Fade,
} from '@mui/material';
import {
  Mic,
  MicOff,
  Videocam,
  VideocamOff,
  Fullscreen,
  FullscreenExit,
  Person,
} from '@mui/icons-material';
import { Participant } from '@/types';

interface VideoContainerProps {
  localStream: MediaStream | null;
  remoteStream: MediaStream | null;
  isAudioEnabled: boolean;
  isVideoEnabled: boolean;
  participants: Participant[];
}

const VideoContainer: React.FC<VideoContainerProps> = ({
  localStream,
  remoteStream,
  isAudioEnabled,
  isVideoEnabled,
  participants,
}) => {
  const localVideoRef = useRef<HTMLVideoElement>(null);
  const remoteVideoRef = useRef<HTMLVideoElement>(null);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [hoveredVideo, setHoveredVideo] = useState<'local' | 'remote' | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  // 设置本地视频流
  useEffect(() => {
    if (localVideoRef.current && localStream) {
      localVideoRef.current.srcObject = localStream;
    }
  }, [localStream]);

  // 设置远程视频流
  useEffect(() => {
    if (remoteVideoRef.current && remoteStream) {
      remoteVideoRef.current.srcObject = remoteStream;
    }
  }, [remoteStream]);

  // 全屏处理
  const handleFullscreen = async () => {
    if (!containerRef.current) return;

    try {
      if (!isFullscreen) {
        await containerRef.current.requestFullscreen();
        setIsFullscreen(true);
      } else {
        await document.exitFullscreen();
        setIsFullscreen(false);
      }
    } catch (error) {
      console.error('全屏操作失败:', error);
    }
  };

  // 监听全屏状态变化
  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement);
    };

    document.addEventListener('fullscreenchange', handleFullscreenChange);
    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    };
  }, []);

  // 获取远程参与者信息
  const remoteParticipant = participants.find(p => p.id !== 'local');

  return (
    <Box
      ref={containerRef}
      sx={{
        flex: 1,
        display: 'flex',
        gap: 2,
        minHeight: 400,
        position: 'relative',
      }}
    >
      {/* 远程视频 - 主视频 */}
      <Paper
        elevation={3}
        sx={{
          flex: 1,
          borderRadius: 2,
          overflow: 'hidden',
          position: 'relative',
          backgroundColor: '#000',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
        onMouseEnter={() => setHoveredVideo('remote')}
        onMouseLeave={() => setHoveredVideo(null)}
      >
        {remoteStream ? (
          <video
            ref={remoteVideoRef}
            autoPlay
            playsInline
            style={{
              width: '100%',
              height: '100%',
              objectFit: 'cover',
            }}
          />
        ) : (
          <Box
            sx={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: 2,
              color: 'white',
            }}
          >
            <Avatar
              sx={{
                width: 80,
                height: 80,
                backgroundColor: 'primary.main',
              }}
            >
              <Person sx={{ fontSize: 40 }} />
            </Avatar>
            <Typography variant="h6" color="inherit">
              {remoteParticipant ? `等待 ${remoteParticipant.id} 加入...` : '等待其他人加入...'}
            </Typography>
          </Box>
        )}

        {/* 远程视频控制覆盖层 */}
        <Fade in={hoveredVideo === 'remote'}>
          <Box
            sx={{
              position: 'absolute',
              top: 16,
              right: 16,
              display: 'flex',
              gap: 1,
            }}
          >
            <Tooltip title={isFullscreen ? '退出全屏' : '全屏'}>
              <IconButton
                onClick={handleFullscreen}
                sx={{
                  backgroundColor: 'rgba(0, 0, 0, 0.5)',
                  color: 'white',
                  '&:hover': {
                    backgroundColor: 'rgba(0, 0, 0, 0.7)',
                  },
                }}
              >
                {isFullscreen ? <FullscreenExit /> : <Fullscreen />}
              </IconButton>
            </Tooltip>
          </Box>
        </Fade>

        {/* 远程参与者信息 */}
        {remoteParticipant && (
          <Box
            sx={{
              position: 'absolute',
              bottom: 16,
              left: 16,
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              backgroundColor: 'rgba(0, 0, 0, 0.5)',
              borderRadius: 1,
              px: 2,
              py: 1,
            }}
          >
            <Typography variant="body2" color="white" sx={{ fontWeight: 600 }}>
              {remoteParticipant.id}
            </Typography>
            {/* 这里可以显示远程参与者的音视频状态 */}
          </Box>
        )}
      </Paper>

      {/* 本地视频 - 画中画 */}
      <Paper
        elevation={4}
        sx={{
          width: 240,
          height: 180,
          borderRadius: 2,
          overflow: 'hidden',
          position: 'relative',
          backgroundColor: '#000',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          flexShrink: 0,
        }}
        onMouseEnter={() => setHoveredVideo('local')}
        onMouseLeave={() => setHoveredVideo(null)}
      >
        {localStream && isVideoEnabled ? (
          <video
            ref={localVideoRef}
            autoPlay
            playsInline
            muted
            style={{
              width: '100%',
              height: '100%',
              objectFit: 'cover',
              transform: 'scaleX(-1)', // 镜像显示
            }}
          />
        ) : (
          <Box
            sx={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: 1,
              color: 'white',
            }}
          >
            <Avatar
              sx={{
                width: 48,
                height: 48,
                backgroundColor: 'primary.main',
              }}
            >
              <Person sx={{ fontSize: 24 }} />
            </Avatar>
            <Typography variant="caption" color="inherit">
              {isVideoEnabled ? '加载中...' : '摄像头已关闭'}
            </Typography>
          </Box>
        )}

        {/* 本地视频状态指示器 */}
        <Fade in={hoveredVideo === 'local' || !isAudioEnabled || !isVideoEnabled}>
          <Box
            sx={{
              position: 'absolute',
              bottom: 8,
              right: 8,
              display: 'flex',
              gap: 0.5,
            }}
          >
            {!isAudioEnabled && (
              <IconButton
                size="small"
                sx={
                  {
                    backgroundColor: 'error.main',
                    color: 'white',
                    width: 24,
                    height: 24,
                    '&:hover': {
                      backgroundColor: 'error.dark',
                    },
                  }
                }
              >
                <MicOff sx={{ fontSize: 14 }} />
              </IconButton>
            )}
            {!isVideoEnabled && (
              <IconButton
                size="small"
                sx={{
                  backgroundColor: 'error.main',
                  color: 'white',
                  width: 24,
                  height: 24,
                  '&:hover': {
                    backgroundColor: 'error.dark',
                  },
                }}
              >
                <VideocamOff sx={{ fontSize: 14 }} />
              </IconButton>
            )}
          </Box>
        </Fade>

        {/* 本地用户标识 */}
        <Box
          sx={{
            position: 'absolute',
            top: 8,
            left: 8,
            backgroundColor: 'rgba(0, 0, 0, 0.5)',
            borderRadius: 1,
            px: 1,
            py: 0.5,
          }}
        >
          <Typography variant="caption" color="white" sx={{ fontWeight: 600 }}>
            您
          </Typography>
        </Box>
      </Paper>
    </Box>
  );
};

export default VideoContainer;